package com.hehe.strategy.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hehe.model.SecurityUser;
import com.hehe.powernode.constant.AuthConstants;
import com.hehe.powernode.mapper.LoginSysUserMapper;
import com.hehe.powernode.pojo.LoginSysUser;
import com.hehe.strategy.LoginStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Set;

@Slf4j
@Service(AuthConstants.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {
    @Autowired
    private LoginSysUserMapper loginSysUserMapper;
    /**
     * 编写后台管理系统用户的登录逻辑
     * @param username
     * @return
     */
    @Override
    public UserDetails realLogin(String username) {
        log.info("realLogin username:{}",username);
        LambdaQueryWrapper<LoginSysUser> lambdaQueryWrapper = new LambdaQueryWrapper<LoginSysUser>();
        lambdaQueryWrapper.eq(LoginSysUser::getUsername,username);
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(lambdaQueryWrapper);
        log.info("realLogin loginSysUser:{}",loginSysUser);
        // 判断用户是否存在
        if (!ObjectUtils.isEmpty(loginSysUser)) {
            SecurityUser securityUser = new SecurityUser();
            // 用户存在，查询用户的权限
            Set<String> perms = loginSysUserMapper.selectPermsBySysUserId(loginSysUser.getUserId());
            securityUser.setUserId(loginSysUser.getUserId());
            securityUser.setUsername(loginSysUser.getUsername());
            securityUser.setPassword(loginSysUser.getPassword());
            securityUser.setLoginType(AuthConstants.SYS_USER_LOGIN);
            securityUser.setShopId(loginSysUser.getShopId());
            securityUser.setStatus(loginSysUser.getStatus());
            // 判断用户是否有权限
            if (!CollectionUtils.isEmpty(perms) && !perms.isEmpty()) {
                securityUser.setPerms(perms);
            }
            return securityUser;
        }
        return null;
    }
}
